<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      :page="page"
      @row-del="rowDel"
      v-model="form"
      @row-save="rowSave"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" plain @click="addShare">新增分享福利</el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" plain @click="addTrade">新增交易福利</el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          plain
          @click="settingArea"
        >设置福利领取区域</el-button>
      </template>
    </avue-crud>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%">
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
          style="width:50%;"
        >
          <el-form-item label="课程名称" prop="name">
            <!-- <el-input v-model="ruleForm.name"></el-input> -->
            <el-select v-model="ruleForm.name" placeholder="请选择课程" @change="getCourseId">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in courseSelection"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="福利类型" prop="welfareType">
            <el-select v-model="ruleForm.welfareType" placeholder="请选择福利类型" @change="getValue">
              <el-option label="现金福利" value="1"></el-option>
              <el-option label="代金券福利" value="2"></el-option>
              <el-option label="礼品福利" value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="总金额" prop="amount" v-if="values==1">
            <el-input v-model="ruleForm.amount"></el-input>
          </el-form-item>
          <el-form-item label="折扣金额" prop="discount" v-if="values==2">
            <el-input v-model="ruleForm.discount"></el-input>
          </el-form-item>
          <el-form-item label="礼品" prop="giftName" v-if="values==3">
            <el-input v-model="ruleForm.giftName"></el-input>
          </el-form-item>
          <el-form-item label="福利数" prop="count">
            <el-input v-model="ruleForm.count"></el-input>
          </el-form-item>
          <el-form-item label="福利解锁条件" prop="unlockCondition">
            <el-select
              v-model="ruleForm.unlockCondition"
              placeholder="请选择福利解锁条件"
              @change="getConditions"
            >
              <el-option label="新用户查看次数" value="1"></el-option>
              <el-option label="分享次数" value="2"></el-option>
              <el-option label="咨询次数" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="次数" prop="times">
            <el-input v-model="ruleForm.times"></el-input>
          </el-form-item>
          <el-form-item label="分配方式" prop="assignType" v-if="values==1">
            <el-select v-model="ruleForm.assignType" placeholder="请选择分配方式" @change="getDelivery">
              <el-option label="均分" value="1"></el-option>
              <el-option label="随机" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增交易福利 -->
    <el-dialog title="提示" :visible.sync="dialogVisible1" width="50%">
      <div>
        <el-form
          :model="tradeForm"
          :rules="rules"
          ref="tradeForm"
          label-width="120px"
          class="demo-ruleForm"
          style="width:50%;"
        >
          <el-form-item label="课程名称" prop="name">
            <!-- <el-input v-model="ruleForm.name"></el-input> -->
            <el-select v-model="tradeForm.name" placeholder="请选择课程" @change="getCourseId">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in courseSelection"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="福利类型" prop="welfareType">
            <el-select v-model="tradeForm.welfareType" placeholder="请选择福利类型" @change="getValue">
              <el-option label="现金福利" value="1"></el-option>
              <el-option label="返佣" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="返佣比例" prop="rebate" v-if="values==2">
            <el-input v-model="tradeForm.rebate" style="width:60%"></el-input>%
          </el-form-item>
          <el-form-item label="总金额" prop="amount" v-if="values==1">
            <el-input v-model="tradeForm.amount"></el-input>
          </el-form-item>

          <el-form-item label="福利数" prop="count" v-if="values==1">
            <el-input v-model="tradeForm.count"></el-input>
          </el-form-item>
          <el-form-item label="报名人数" prop="giftName" v-if="values==1">
            <el-input v-model="tradeForm.giftName"></el-input>
          </el-form-item>

          <el-form-item label="分配方式" prop="assignType" v-if="values==1">
            <el-select v-model="tradeForm.assignType" placeholder="请选择分配方式" @change="getDelivery">
              <el-option label="均分" value="1"></el-option>
              <el-option label="随机" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitFormTrade('tradeForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 福利领取区域 -->

    <el-dialog title="提示" :visible.sync="dialogVisible2" width="50%">
      <div>
        <el-form
          :model="settingForm"
          :rules="rules"
          ref="tradeForm"
          label-width="130px"
          class="demo-ruleForm"
          style="width:50%;"
        >
          <el-form-item label="经度">
            <el-input v-model="settingForm.x" disabled></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input v-model="settingForm.y" disabled></el-input>
          </el-form-item>
          <el-form-item label="获取半径（米）" prop="scope">
            <el-input v-model="settingForm.scope" @input="changeMap" type="number"></el-input>
          </el-form-item>
          <baidu-map
            class="map"
            :center="circlePath.center"
            :zoom="15"
            :scroll-wheel-zoom="true"
            @click="getClickInfo"
          >
            <bm-circle
              :center="circlePath.center"
              :radius="circlePath.radius"
              stroke-color="blue"
              :stroke-opacity="0.5"
              :stroke-weight="2"
              @lineupdate="updateCirclePath"
              :editing="true"
            ></bm-circle>
            <bm-control>
              <div style="display:flex;margin:5px">
                <el-input
                  placeholder="请输入地址"
                  style="margin-right:20px;width:300px;"
                  v-model="keyword"
                ></el-input>
                <el-button type="primary" @click="searchMap">搜索</el-button>
                <el-button type="primary" @click="getPoints">拾取坐标</el-button>
              </div>
            </bm-control>

            <bm-local-search :keyword="keyword" :auto-viewport="true"></bm-local-search>
          </baidu-map>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitSettingArea(settingForm)">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import {
  courceListShare,
  addWare,
  courseList,
  removeBuy,
  addTrade,
  searchBuy,
  settingArea,
  removeShare
} from "@/api/course/courseDetail";
export default {
  data() {
    return {
      data: [],
      circlePath: {
        center: {
          lng: 0,
          lat: 0
        },
        radius: 0
      },
      keyword: "",
      page: {
        pageSize: 1000000,
        currentPage: 1,
        total: 0
      },
      courseSelection: [],
      courseId: "",
      ruleForm: {
        name: "",
        welfareType: "",
        amount: "",
        count: "",
        times: "",
        unlockCondition: "",
        assignType: "",
        discount: "",
        giftName: ""
      },
      tradeForm: {
        name: "",
        welfareType: "",
        amount: "",
        count: "",
        times: "",
        unlockCondition: "",
        assignType: "",
        discount: "",
        giftName: ""
      },
      settingForm: {
        id: 1,
        courseId: 1,
        scope: 0,
        x: "", //纬度
        y: "" //经度
      },
      form: {},
      rules: {
        name: [{ required: true, message: "请选择课程", trigger: "blur" }],
        discount: [
          { required: true, message: "请输入抵扣金额", trigger: "blur" }
        ],
        giftName: [
          { required: true, message: "请输入礼品名称", trigger: "blur" }
        ],
        rebate: [
          { required: true, message: "请输入返佣比例", trigger: "blur" }
        ],
        welfareType: [
          { required: true, message: "请选择福利类型", trigger: "change" }
        ],
        amount: [{ required: true, message: "请输入总金额", trigger: "blur" }],
        count: [{ required: true, message: "请输入福利数", trigger: "blur" }],
        times: [{ required: true, message: "请输入次数", trigger: "blur" }],
        unlockCondition: [
          { required: true, message: "请选择解锁条件", trigger: "change" }
        ],
        assignType: [
          { required: true, message: "请选择分配方式", trigger: "change" }
        ]
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      values: "",
      conditions: "",
      delivery: "",
      option: {
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        columnBtn: false,
        refreshBtn: false,
        searchBtn: false,
        editBtn: true,
        addBtn: false,
        delBtn: true,
        column: [
          {
            label: "课程名称",
            prop: "name",
            search: false
          },
          {
            label: "福利种类",
            prop: "state",
            search: false
          },
          {
            label: "福利类型",
            prop: "welfareType",
            search: false
          },
          {
            label: "福利获取条件",
            prop: "unlockCondition",
            search: false
          }
        ]
      }
    };
  },
  created() {
    const row = this.$route.query.row;
    const id = row.id;
    console.log(row)
    this.courseId = row.id;
    // 获取所有课程
    courseList(1, "", 1000000).then(res => {
      this.courseSelection = res.data.data.records;
    });

    searchBuy(id).then(res => {
      console.log(res)
      this.form = res.data.data;
      this.circlePath.center.lng = this.form.y;
      this.circlePath.center.lat = this.form.x;
      this.circlePath.radius = this.form.scope;
      this.settingForm.x = this.form.y;
      this.settingForm.y = this.form.x;
      this.settingForm.scope = this.form.scope;
      this.settingForm.id = this.form.id,
      this.settingForm.courseId = this.form.activityId
    });
  },
  methods: {
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          console.log("success");
          addWare(this.ruleForm).then(res => {
            console.log(res);
            console.log(res);
            this.$message({
              type: "success",
              message: res.data.msg
            });
            this.dialogVisible = false;
            this.onLoad(this.page);
          });
        } else {
          console.log("error");
        }
      });
    },
    submitFormTrade(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          console.log("success");
          addTrade(this.tradeForm).then(res => {
            console.log(res);
            this.$message({
              type: "success",
              message: res.data.msg
            });
            this.dialogVisible1 = false;
            this.onLoad(this.page);
          });
        } else {
          console.log("error");
        }
      });
    },
    searchMap() {
      if (this.keyword == "") {
        this.$message({
          type: "error",
          message: "搜索地址不能为空"
        });
      } else {
      }
    },

    // 点击地图获取经纬度
    getClickInfo(e) {
      console.log(e);
      if (this.settingForm.scope == "" || this.settingArea.scope == 0) {
        this.$message({
          type: "error",
          message: "请输入福利半径"
        });
      } else {
        this.settingForm.x = e.point.lng;
        this.settingForm.y = e.point.lat;
        this.circlePath.center.lng = e.point.lng;
        this.circlePath.center.lat = e.point.lat;
        this.circlePath.radius = this.settingForm.scope;
      }
    },
    // 拾取坐标
    getPoints() {
      this.$message({
        type: "warn",
        message: "请直接点击地图上的位置进行坐标获取"
      });
    },

    // 监听半径变化重绘地图，此处重绘地图可以封装成公共方法，TODO
    changeMap(e) {
      if (e != "" && e != 0) {
        this.circlePath.radius = e;
      } else {
        this.$message({
          type: "erro",
          message: "请检查输入项"
        });
      }
    },
    // 提交修改区域半径
    submitSettingArea(form) {
      this.settingForm.scope = +this.settingForm.scope;
      // console.log(form)
      settingArea(this.settingForm).then(res => {
        this.dialogVisible2 = false;
        this.onLoad(this.page);
      });
    },
    getCourseId(val) {
      this.courseId = val;
      this.ruleForm.courseId = val;
      this.tradeForm.courseId = val;
    },
    getValue(val) {
      this.values = val;
    },
    getConditions(val) {
      this.conditions = val;
      console.log(val);
    },
    getDelivery() {
      this.delivery = val;
      console.log(val);
    },
    addShare() {
      this.dialogVisible = true;
    },
    addTrade() {
      this.dialogVisible1 = true;
    },
    settingArea() {
      this.dialogVisible2 = true;
    },
    updateCirclePath(e) {
      this.circlePath.center = e.target.getCenter();
      this.circlePath.radius = e.target.getRadius();
    },
    rowSave(row, loading, done) {
      add(row).then(
        () => {
          loading();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        },
        error => {
          done();
          console.log(error);
        }
      );
    },
    rowUpdate(row, index, loading, done) {
      update(row).then(
        () => {
          loading();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        },
        error => {
          done();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (row.state === "分享") {
            return removeShare(row.id);
          }
          if (row.state === "交易") {
            return removeBuy(row.id);
          }
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.onLoad(this.page);
    },
    searchChange(params) {
      this.onLoad(this.page, params);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getNotice(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      const { releaseTimeRange } = params;
      let values = {
        ...params
      };
      if (releaseTimeRange) {
        values = {
          ...params,
          releaseTime_gt: releaseTimeRange[0],
          releaseTime_lt: releaseTimeRange[1]
        };
        values.releaseTimeRange = null;
      }
      courceListShare(this.courseId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data;
      });
    }
  }
};
</script>
<style>
.none-border {
  border: 0;
  background-color: transparent !important;
}
.map {
  width: 800px;
  height: 400px;
}
</style>
